<template>
    <!-- 表单 -->
    <div>
        <el-form :model="pageParams" label-width="auto" style="margin-top: 20px;margin-left: 30px;">
            <el-row>
                <el-col :span="5">
                    <el-form-item label="活动名称">
                        <el-input v-model="pageParams.name" placeholder="请输入活动名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="渠道名称" style="margin-left: 35px;">
                        <!-- :label指的是下拉框选项显示的文本内容   :value绑定该表单数据的参数 -->
                        <el-select size="large" v-model="pageParams.channelId" placeholder="请选择渠道"
                            style="font-size: 20px;">
                            <el-option v-for="item in options" :key="item.value" :label="item.channelName"
                                :value="item.channelId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="活动状态" style="margin-left: 65px;">
                        <!-- :label指的是下拉框选项显示的文本内容   :value绑定该表单数据的参数 -->
                        <el-select size="large" v-model="pageParams.status" placeholder="请选择渠道"
                            style="font-size: 20px;">
                            <el-option v-for="item in statusOption" :key="item.value" :label="item.dictLabel"
                                :value="item.dictValue">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="活动类型" style="margin-left: 95px;">
                        <!-- :label指的是下拉框选项显示的文本内容   :value绑定该表单数据的参数 -->
                        <el-select size="large" v-model="pageParams.type" placeholder="请选择渠道" style="font-size: 20px;"
                            @change="bclxChange">
                            <el-option v-for="item in typeOption" :key="item.value" :label="item.dictLabel"
                                :value="item.dictValue">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
                    <el-button :icon="Refresh">重置</el-button>
                </el-form-item>
            </el-row>
            <!-- 按钮 -->
            <div>
                <el-row style="display: flex;justify-content: space-between;">
                    <el-form-item>
                        <el-button type="primary" :icon="Plus" plain @click="add">新增</el-button>
                        <el-button type="success" :icon="Edit" plain @click="edit()">修改</el-button>
                        <el-button type="danger" :icon="Delete" plain @click="del()">删除</el-button>
                        <el-button type="warning" :icon="Download" plain>导出</el-button>
                    </el-form-item>
                    <el-form-item style="margin-left: 35px; width: 100px;">
                        <el-button :icon="Search" circle />
                        <el-button :icon="Refresh" circle />
                    </el-form-item>
                </el-row>
            </div>
        </el-form>
    </div>
    <!-- 表格 -->
    <div>
        <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column prop="activityId" label="活动编号" width="120">
            </el-table-column>
            <el-table-column prop="name" label="活动名称" width="120" />
            <el-table-column prop="channelName" label="渠道名称" />
            <el-table-column prop="info" label="活动简介" />
            <el-table-column prop="type" label="活动类型" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.type == 1">折扣券</el-tag>
                    <el-tag type="success" v-if="scope.row.type == 2">代金券</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="voucher" label="活动明细">
                <template #default="scope">
                    {{ scope.row.type }}/{{ scope.row.voucher }}元
                </template>
            </el-table-column>
            <el-table-column prop="status" label="活动状态" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.status == 1">正常</el-tag>
                    <el-tag type="success" v-if="scope.row.status == 0">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column property="beginTime" label="活动起始时间" />
            <el-table-column property="endTime" label="活动结束时间" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button link type="primary" :icon="Edit" @click="editdata(scope.row.activityId)">
                        修改
                    </el-button>
                    <el-button link type="primary" :icon="Delete" @click.prevent="deldata(scope.row.activityId)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 对话框 -->
    <el-dialog :title="title" v-model="editDialog" width="50%">
        <div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select size="small" v-model="ruleForm.channelId" placeholder="请选择"
                                @change="channelChange">
                                <el-option v-for="item in options" :key="item.value" :label="item.channelName"
                                    :value="item.channelId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="活动名称" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请输入活动名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="活动日期" prop="activityTime">
                            <el-date-picker v-model="ruleForm.activityTime" type="datetimerange"
                                start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
                                @change="time" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="活动简介" prop="info">
                            <el-input size="small" v-model="ruleForm.info"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="活动类型" prop="type">
                            <!-- :label指的是下拉框选项显示的文本内容   :value绑定该表单数据的参数 -->
                            <el-select size="large" v-model="ruleForm.type" placeholder="请选择渠道" style="font-size: 20px;"
                                @change="bclxChange">
                                <el-option label="折扣券" value="1" />
                                <el-option label="代金券" value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="折扣券" v-if="isJxBc" prop="discount">
                        <el-input-number v-model="ruleForm.discount" :min="1" :max="1000" label="描述文字"
                            placeholder="请输入折扣值" style="width: 240px;"></el-input-number>
                    </el-form-item>
                    <el-form-item label="代金券" v-if="isMoney" prop="voucher">
                        <el-input-number v-model="ruleForm.voucher" :min="1" :max="1000" label="描述文字"
                            placeholder="请输入代金券面值" style="width: 240px;"></el-input-number>
                    </el-form-item>
                </el-row>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="EditSubmitForm(ruleFormRef)">确定</el-button>
            <el-button @click="EditResetForm(ruleFormRef)">取消</el-button>
        </span>
    </el-dialog>
    <!-- 分页器 -->
    <page :pageParams="pageParams" :total="total" @size-change="pageChange" @currentChange="handleCurrentChange">
    </page>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, computed } from 'vue';
import page from "../../../components/Pagination/page.vue";
// import { activity, treeselect, detail } from "../../../api/list"
import { list, channel, statusData, typeData, addData, editData, updata, delData } from "../../../api/act";
import { Search, Refresh, Plus, Edit, Delete, Pointer, Download, TopRight, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import type { TableInstance, FormInstance, FormRules, ComponentSize } from 'element-plus'
import router from '@/router';



// 性别
const sex = [
    {
        label: "男",
        value: 0
    }, {
        label: "女",
        value: 1
    }, {
        label: "未知",
        value: 2
    },
]
// 搜索按钮
const search = () => {
    pageParams.pageNum = 1
    getList()
}

// 时间日期
const value1 = ref<[Date, Date]>([
    //   new Date(2000, 10, 10, 10, 10),
    //   new Date(2000, 10, 11, 10, 10),
])


// 新增按钮
function add() {
    editDialog.value = true
    title.value = "添加活动"
    // 重置表单
    nextTick(() => {
        ruleFormRef.value.resetFields()
    })
}


// 编辑按钮 多选
function edit(row: any) {
    // if(val) {
    //     idList[0].value = val
    // }
    editDialog.value = true;
    title.value = "修改商机";
    // 获取详情
    editData(row).then(res => {
        console.log(row);

        ruleForm.value.name = res.data.name;
        ruleForm.value.channelId = res.data.channelId;
        ruleForm.value.info = res.data.info;
        ruleForm.value.type = res.data.type;
        ruleForm.value.discount = res.data.discount;
        // ruleForm.value.voucher = res.data.voucher;
        ruleForm.value.activityTime = res.data.activityTime;
        // if(res.data.channelId) {
        //    ruleForm.channelId = res.data.channelId
        //     // 再次调用活动列表
        //     channelChange(res.data.channelId)
        //     ruleForm.activityId = res.data.activityId
        // }
    })
}

function editdata(id: number) {
    // if(val) {
    //     idList[0].value = val
    // }
    editDialog.value = true;
    title.value = "修改商机";
    // 获取详情
    editData(id).then(res => {
        ruleForm.value.name = res.data.name;
        ruleForm.value.channelId = res.data.channelId;
        ruleForm.value.info = res.data.info;
        ruleForm.value.type = res.data.type;
        ruleForm.value.discount = res.data.discount;
        // ruleForm.value.voucher = res.data.voucher
        ruleForm.value.activityTime = res.data.activityTime;
        // if(res.data.channelId) {
        //    ruleForm.channelId = res.data.channelId
        //     // 再次调用活动列表
        //     channelChange(res.data.channelId)
        //     ruleForm.activityId = res.data.activityId
        // }
    })
}
// 编辑对话框
let title = ref('')
const editDialog = ref(false)


// function time() {
//     ruleForm.value.beginTime = ruleForm.value.activityTime[0]
//     ruleForm.value.endTime = ruleForm.value.activityTime[1]

// }
function formatDate(isoString: string): string {
    const date = new Date(isoString);
    // 处理时区偏移（转为北京时间：UTC+8）
    const offset = date.getTimezoneOffset() * 60000; // 本地时区与UTC的时差（毫秒）
    const beijingTime = new Date(date.getTime() + offset + 8 * 3600000);

    // 补零函数
    const pad = (num: number) => num.toString().padStart(2, '0');

    const year = beijingTime.getFullYear();
    const month = pad(beijingTime.getMonth() + 1); // 月份从0开始
    const day = pad(beijingTime.getDate());
    const hours = pad(beijingTime.getHours());
    const minutes = pad(beijingTime.getMinutes());
    const seconds = pad(beijingTime.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 在time()方法中调用
function time() {
    const [start, end] = ruleForm.value.activityTime;
    if (start) ruleForm.value.beginTime = formatDate(start as string);
    if (end) ruleForm.value.endTime = formatDate(end as string);
}
// dialog弹框的
const EditSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === "添加活动") {
                // 新增接口
                addData(ruleForm.value).then(res => {
                    console.log(res);

                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    });
                    getList();
                    editDialog.value = false;
                });
            } else {
                // 修改
                // ruleForm.value.activityId = idList.value
                updata(ruleForm.value
                ).then(res => {
                    ElMessage.success("修改成功")
                    editDialog.value = false
                })

            }
        } else {
            console.log('error submit!', fields)
        }

    })
}
// 编辑提交表单

// 取消按钮
const EditResetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    editDialog.value = false
}

// 删除按钮
function del() {
    ElMessageBox.confirm(
        `此操作将永久删除编号为${idList.value}的数据, 是否继续?`,
        '系统提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            delData(idList.value).then(res => {
                getList()
                ElMessage({
                    type: 'warning',
                    message: '删除成功',
                })
            })
        })
}
function deldata(id: number) {
    ElMessageBox.confirm(
        `此操作将永久删除编号为${id}的数据, 是否继续?`,
        '系统提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            delData(
                id
            ).then(res => {
                ElMessage.success('删除成功')
                getList()
            })
        })

}
// 删除
// function del(id: number) {
//     userdel({
//         id: id
//     }).then(res => {
//         ElMessage.success('删除成功')
//         getList()
//     })
// }


// 表格
interface User {
    id: number
    date: string
    name: string
    address: string
    tag: string,
    activityId: string
}

const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])

const idList = ref()
const selectable = (row: User) => ![1, 2].includes(row.id)
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
    console.log(val)
    const info = JSON.parse(JSON.stringify(val))
    console.log(info)
    idList.value = val[0].activityId
    console.log(idList.value)
}

// 表格数据
const tableData: any = ref([])

// 查看按钮
function check() {
    console.log('当前行线索ID:', idList.value);
    router.push({ path: `/business/details/index/${idList.value}/view` });
}

// 修改对话框的数据
// interface RuleForm {
//     name: string,
//     type: string,
//     activityId: number,
//     beginTime: string,
//     endTime: string,
//     activityTime: [],
//     discount: null,
//     voucher: null,
//     info: string,
//     channelId: null

// }
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
    name: '',
    type: '',
    activityId: null,
    beginTime: '',
    endTime: '',
    activityTime: [],
    discount: null,
    // voucher: null,
    info: '',
    channelId: null
})
const rules = reactive<FormRules<RuleForm>>({
    channelId: [
        {
            required: true,
            message: '渠道来源不能为空',
            trigger: 'change',
        },
    ],
    name: [
        {
            required: true,
            message: '活动名称不能为空',
            trigger: 'change',
        },
    ],
    activityTime: [
        {
            required: true,
            message: '活动时间不能为空',
            trigger: 'change',
        },
    ],
    info: [
        {
            required: true,
            message: '活动简介不能为空',
            trigger: 'change',
        },
    ],
    type: [
        {
            required: true,
            message: '活动类型不能为空',
            trigger: 'change',
        },
    ],
    discount: [
        {
            required: true,
            message: '折扣券不能为空',
            trigger: 'change',
        },
    ],
    voucher: [
        {
            required: true,
            message: '代金券不能为空',
            trigger: 'change',
        },
    ],
})
// 树形选择器
const label = ref()
const data = [
    {
        label: '',
        children: [{}]
    }
    // {
    //     value: '1',
    //     label: 'Level one 1',
    //     children: [
    //         {
    //             value: '1-1',
    //             label: 'Level two 1-1',
    //             children: [
    //                 {
    //                     value: '1-1-1',
    //                     label: 'Level three 1-1-1',
    //                 },
    //             ],
    //         },
    //     ],
    // }
]


// // 跟进按钮
// function follow(){
//     console.log("跟进")
// }


// 折扣券和代金券的显示隐藏
const isMoney = ref(false)
const isJxBc = ref(false)
function bclxChange(selectLabel) {
    if (selectLabel === '1') {
        isJxBc.value = true
        isMoney.value = false
    }
    else if (selectLabel === '2') {
        isMoney.value = true
        isJxBc.value = false
    }
    else {
        isJxBc.value = false
        isMoney.value = false
    }
}

// 分页器
let total = ref(0)
// id
let id = ref(0)
const pageParams = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    channelId: '',
    status: '',
    type: ''
})
onMounted(() => {
    getList()
})


// 渠道来源发生变化时触发
function channelChange(val) {
    // 每次获取完渠道来源的时候，把活动信息的数据清空，每个渠道来源对应的活动信息数据都是不同的
    ruleForm.activityId = null
    // 渠道来源发生变化的时候，渲染出活动信息的数据
    activity(val).then(res => {
        actOption.value = res.data
    })
}

// 渠道名称
const options = ref()
// 活动状态
const statusOption = ref()
// 活动类型
const typeOption = ref()

const actOption = ref()
function getList() {
    list(pageParams).then(res => {
        console.log(res)
        tableData.value = res.rows
        total.value = res.total
    })
    // treeselect().then(res => {
    //     console.log(res)
    //     data.value = res.data
    //     data.children = res.data.children
    //     data.label = res.data.label
    // })
    // 渠道名称
    channel().then(res => {
        options.value = res.data
    })
    // 活动状态
    statusData().then(res => {
        statusOption.value = res.data
    })
    // 活动类型
    typeData().then(res => {
        typeOption.value = res.data
    })
}


// 定义开始时间和结束时间
const beginTime = ref('');
const endTime = ref('');

// 计算属性实现activityTime与beginTime/endTime的双向绑定
const activityTime = computed({
    get() {
        // 从beginTime和endTime组合成数组
        return [beginTime.value, endTime.value];
    },
    set(newValue) {
        // 当选择器值变化时，将数组值分别赋给beginTime和endTime
        if (Array.isArray(newValue) && newValue.length === 2) {
            [beginTime.value, endTime.value] = newValue;
            console.log('开始时间:', beginTime.value);
            console.log('结束时间:', endTime.value);
        }
    }
});

// 分页器
// 接收子传父数据 条数改变时
const pageChange = (val: number) => {
    pageParams.pageNum = 1
    pageParams.pageSize = val
    getList()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    pageParams.pageNum = val
    getList()
}

</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
    --el-input-width: 100px;
}

:deep(.el-form-item__label) {
    font-size: 16px;
    font-weight: 600;
}

:deep(.el-input__wrapper) {
    width: 240px;
    height: 35px;
}
</style>